var roomId = 1;
var roomName = 1;
var title = " ";
var calendar;
var ownerId;

var startUsedForAddTheme;
var endUsedForAddTheme; 

$(document).ready(function() {
	getAllMeetingRooms();
	//var date = new Date();
	//var d = date.getDate();
	//var m = date.getMonth();
	//var y = date.getFullYear();
	calendar = $('#calendar').fullCalendar({
		header: {
			left: 'prev,next today',
			center: 'title',
			right: 'month,agendaWeek,agendaDay'
		},//
		lazyFetching : false, //
		defaultView:'agendaWeek',//
		firstDay:1,//
		allDaySlot: false,//
		allDayDefault: false,//
		buttonText: {today: '今天',month: '月',week: '周',	day: '日'},//
		monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],//
		monthNamesShort: ['1','2','3','4','5','6','7','8','9','10','11','12'],//
		dayNames: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],//
		dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],//
		
		timeFormat: {agenda: 'h:mmtt{ - h:mmtt}', '': 'h(:mm)tt'},//
		
		columnFormat: {	month: 'ddd',week: 'MM/dd ddd',	day: 'ddd'	},//
		
		titleFormat: {month: 'yyyy 年 MMM 月',week: "yyyy.MM.dd{ '&#8212;' yyyy.MM.dd}",day: 'ddd'	},//
		snapMinutes : 5,//
		slotEventOverlap : false,//
		selectable: true,//
		selectHelper: true,//
		
		minTime : '09:00:00',//
		maxTime : '18:00:00',//
		
		select: select,//
		eventDrop: eventDrop,//
		eventClick: eventClick,//
		editable: true,
		events: function( start, end, callback ) {
			$.post(ctx + '/roomSchedule/dataGrid',{
					roomid: roomId,
					start:Math.round(start.getTime()/1000),
					end:Math.round(end.getTime()/1000),
			}, function(events){
				var objs = jQuery.parseJSON(events);
				callback(objs.obj);
			});
		},//
		eventResize :eventResize,//
	});
	
});
function getAllMeetingRooms() {
	$.getJSON(ctx + '/room/dataGrid','',function(data){
		var str = "";
		roomName = data.rows[0].name;
		for ( var i = 0; i < data.rows.length; i++) {
			str += "<div class='external-event rooms' id=" 
				+ data.rows[i].id + "&" + data.rows[i].name + ">" + data.rows[i].name + "</div>";
		}
		$("#room_name_div").append(str);
		$(".external-event").click(function(){
			$(".external-event").css("border-style","solid ");
			$(this).css("border-style","solid dotted dashed double");
			roomId = this.id.split("&")[0];
			roomName = this.id.split("&")[1];
			calendar.fullCalendar('refetchEvents');
		});
		$(".external-event:first").click();
	});
}
function addFun() {
	parent.$.modalDialog({
		title : '添加',
		width : 500,
		height : 300,
		href : ctx + '/role/addPage',
		buttons : [ {
			text : '添加',
			handler : function() {
				parent.$.modalDialog.openner_dataGrid = d_close;// 因为添加成功之后，需要刷新这个treeGrid，所以先预定义好
				var f = parent.$.modalDialog.handler.find('#roleAddForm');
				f.submit();
			}
		} ]
	});
}
function eventDrop( event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
	var oldEvents = $('#calendar').fullCalendar( 'clientEvents' );
	if(event.start.getTime() <= new Date().getTime()){
		parent.$.messager.alert('提示', "开始时间已过期!", 'info');
		revertFunc();
		return;
	}
	if(isConflict(event,oldEvents)){
		revertFunc();
		return;
	}
	$.post(ctx + '/roomSchedule/updateRoomEvent',
		{ id: event.id,
		  start: event.start.getTime(),
		  end: event.end.getTime(),
		  loginId: loginId
		}, function(data){
			var obj = jQuery.parseJSON(data);
			if(!obj.success){
				parent.$.messager.alert('提示', obj.msg, 'info');
				revertFunc();
			}
		$('#calendar').fullCalendar('refetchEvents'); 
	});
}
function eventClick(calEvent, jsEvent, view) {
	title = calEvent.title;
	var href = ctx + '/order/modifyui?title=' + title 
				+ '&roomName=' + roomName //
				+ '&id=' + calEvent.id //
				+ '&userId=' + sessionInfo_userId;// ;
	href = encodeURI(href); // 进行URL编码
	href = encodeURI(href); 
	parent.$.modalDialog({
		title : '修改',
		width : 300,
		height : 200,
		href : href,
		buttons : [ {
    	   text : '删除事件',
    	   handler : function() {
    		   if(loginName == 'admin' || loginId == parent.ownerId){
	    		   $.post(ctx + '/roomSchedule/deleteRoomEvent',{id: calEvent.id}, function(data){
	    			   var obj = jQuery.parseJSON(data);
	    			   if(!obj.success){
	    				   alert(data.msg);
	    			   }else{
	    				   parent.$.modalDialog.handler.dialog('close');
	    				   $('#calendar').fullCalendar('refetchEvents'); 
	    			   }
	    		   });
    		   }else{
    			   alert("不能删除");
    		   }
    	   }
	       } ,{
				text : '确定',
				handler : function() {
		    	   if(loginName == 'admin' || loginId == parent.ownerId){
		    		   parent.$.modalDialog.update = calendar;//
		    		   var f = parent.$.modalDialog.handler.find('#roleGrantForm');
		    		   f.submit();
		    	   }else{
	    			   alert("不能修改");
	    		   }
				}
			}
		]
		});
}
function select(start, end, allDay) {
	var oldEvents = $('#calendar').fullCalendar( 'clientEvents' );
	var myEvent = new Object();
	myEvent.start = start; 
	myEvent.end = end;
	if(start.getTime() <= new Date().getTime()){
		parent.$.messager.alert('提示', "开始时间已过期!", 'info');
		$('#calendar').fullCalendar('unselect');
		return;

	}else if(isConflict(myEvent,oldEvents)){
		parent.$.messager.alert('提示', "与其他会议冲突！", 'info');
		$('#calendar').fullCalendar('unselect');
		return;
	}else{
		var title = null;
		parent.$.modalDialog({
			title : '添加',
			width : 250,
			height : 200,
			href : ctx + '/roomSchedule/addThemeUI?startTimeForAddTheme=' + start.getTime() + "&endTimeForAddTheme=" + end.getTime() + "&roomId=" + roomId + "&userId=" + sessionInfo_userId,
			buttons : [ {
				text : '添加',
				handler : function() {
					
//					progressLoad();
					myformTemplateId = '${formTemplateId}';
					//parent.$.modalDialog.openner_endUsedForAddTheme = endUsedForAddTheme;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
					parent.$.modalDialog.openner_roomIdForAddTheme = roomId;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
					parent.$.modalDialog.openner_userIdForAddTheme = sessionInfo_userId;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
					parent.$.modalDialog.openner_calendar = calendar;//
					var f = parent.$.modalDialog.handler.find('#eventAddForm');
					f.submit();
					/*var isValid = $(f).form('validate');
					if (!isValid) {
//						progressClose();
						return false;
					}*/
//					var ss = window.parent.document.getElementById("eventStartTimeId").value;
//					alert(ss);
//					alert(window.parent.document.getElementById("endStartTimeId").value);
					/*title = window.parent.document.getElementById("meetingroomtheme").value;
					parent.$.modalDialog.handler.dialog('close');
					
					if (title) {
						$.post(ctx + '/roomSchedule/addRoomEvent',
						{start: start.getTime(), end: end.getTime(), roomId: roomId, title: title,userId : sessionInfo_userId},
						function(data){
							var obj = jQuery.parseJSON(data);
							if(obj.success){
								$('#calendar').fullCalendar('refetchEvents'); 
							}
						});
					}*/
				}
			} ]
		});  
	}
	$('#calendar').fullCalendar('unselect');
}
function eventResize( event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view) { 
	var oldEvents = $('#calendar').fullCalendar( 'clientEvents' );
	if(isConflict(event,oldEvents)){
		revertFunc();
	}
	if(event.start.getTime() <= new Date().getTime()){
		parent.$.messager.alert('提示', "开始时间已过期!", 'info');
		revertFunc();
	}else{
		$.post(ctx + '/roomSchedule/updateRoomEvent',
			{   id: event.id, 
				start: event.start.getTime(),
				end: (event.end.getTime()),
				loginId : loginId
			}, function(data){
			var obj = jQuery.parseJSON(data);
			if(!obj.success){
				parent.$.messager.alert('提示', obj.msg, 'info');
				revertFunc();
			}
			$('#calendar').fullCalendar('refetchEvents'); 
		});
	}
}
function changeRoom(id) {
	$(".external-event").each(function(i) {
		roomId = id;
	});
	$('#calendar').fullCalendar('refetchEvents');
}
function getTipContent(initiator, start, end, subject, contact) {
	$("#initiator").text(initiator);
	$("#contact").text(contact);
	$("#tb").text(
			$.fullCalendar.formatDate(start, 'hh:mmtt') + " - "
			+ $.fullCalendar.formatDate(end, 'hh:mmtt'));
	$("#subject").text(subject);
	return $('#qTipContent');
}
function isConflict(event,oldEvents){
	for ( var i = 0; i < oldEvents.length; i++) {
		var eventStart = event.start.getTime();
		var eventEnd = event.end.getTime();
		var oldEventStart = oldEvents[i].start.getTime();
		var oldEventEnd = oldEvents[i].end.getTime();
		if(        (oldEventStart < eventStart && eventStart < oldEventEnd) 
				|| (oldEventStart < eventEnd && eventEnd < oldEventEnd)
				|| (oldEventStart > eventStart && eventEnd > oldEventEnd)
		){
			return true;
		}
	}
	return false;
}
function meetroomAdd(){
	parent.$.modalDialog({
		title : '添加会议室',
		width : 250,
		height : 100,
		href : ctx + '/order/addRoomUI',
		buttons : [ {
			text : '添加',
			handler : function() {
				var f = parent.$.modalDialog.handler.find('#roomAddForm');
				f.submit();
			}
		} ]
	});
}
function meetroomDel(){
	parent.$.modalDialog({
		title : '删除会议室',
		width : 250,
		height : 100,
		href : ctx + '/order/delRoomUI',
		buttons : [ {
			text : '删除',
			handler : function() {
				var f = parent.$.modalDialog.handler.find('#roomDelForm');
				f.submit();
			}
		} ]
	});
}
function meetroomMod(){
	var href = ctx + '/order/modRoomUI?roomId=' + roomId + '&roomName=' + roomName;
	href = encodeURI(href);
	href = encodeURI(href);
	parent.$.modalDialog({
		title : '修改会议室',
		width : 250,
		height : 100,
		href : href,
		buttons : [ {
			text : '添加',
			handler : function() {
				var f = parent.$.modalDialog.handler.find('#roomModForm');
				f.submit();
			}
		} ]
	});
}
